﻿using BLL.Base;
using BLL.custom;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.SysEntity;
using Entity.ViewEntity;
using Entity.ViewEntity.sys;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BLL
{
    /// <summary>
    /// 系统框架业务逻辑处理方法类
    /// </summary>
    public class SystemBLL : PubMethod
    {
        Commands cmd;
        LoginInfo userLogin;
        Tools.TxtLogHelper txt;
        ReturnResult rsl;
        OperateModel oper;
        public SystemBLL()
        {
            cmd = new Commands();
            userLogin = new LoginInfo();
            txt = new Tools.TxtLogHelper();
            oper = new OperateModel();
        }
        

        #region 用户菜单权限
        /// <summary>
        /// 用户菜单权限
        /// </summary>
        /// <param name="pMenu">父级菜单编码</param>
        /// <param name="qtable">全部菜单</param>
        /// <param name="sTable">显示菜单</param>
        /// <param name="list">菜单编码集合</param>
        private void UserMenuData(string pMenu, DataTable qtable, ref DataTable sTable, ref List<string> list)
        {
            if (!string.IsNullOrWhiteSpace(pMenu))
            {
                if (!list.Contains(pMenu))
                {
                    var dr = qtable.Select("menuCode='" + pMenu + "'");
                    if (dr.Length > 0)
                    {
                        sTable.Rows.Add(dr[0].ItemArray);
                        list.Add(pMenu);
                        UserMenuData(dr[0]["parentMenu"].ToString(), qtable, ref sTable, ref list);
                    }
                }

            }
        }
        #endregion

        #region 创建导航数据
        /// <summary>
        /// 创建导航数据
        /// </summary>
        /// <param name="table">数据源</param>
        /// <returns></returns>
        private List<Dictionary<string, object>> CreateNavigationList(DataTable table)
        {
            List<Dictionary<string, object>> menuList = new List<Dictionary<string, object>>();
            #region 构建数据
            var fMenu = table.Select("menuLevel=1").OrderBy(x => x["orderNum"]).CopyToDataTable();//获取所有父级菜单
            for (int i = 0; i < fMenu.Rows.Count; i++)
            {
                var fdic = new Dictionary<string, object>();
                fdic["menuName"] = fMenu.Rows[i]["menuName"].ToString();
                fdic["menuIcon"] = fMenu.Rows[i]["menuIcon"].ToString();

                #region 子菜单
                List<Dictionary<string, object>> cList = new List<Dictionary<string, object>>();
                this.ChildUrl(table, fMenu.Rows[i]["menuCode"].ToString(), fMenu.Rows[i]["menuName"].ToString(), fMenu.Rows[i]["menuIcon"].ToString(), ref  cList);
                fdic["child"] = cList;
                #endregion
                menuList.Add(fdic);
            }
            #endregion
            return menuList;
        }
        #endregion

        /// <summary>
        /// 子菜单生成方法(递归)
        /// </summary>
        /// <param name="table"></param>
        /// <param name="menuCode"></param>
        /// <param name="menuName"></param>
        /// <param name="icon"></param>
        /// <param name="chlist"></param>
        private void ChildUrl(DataTable table, string menuCode, string menuName, string icon, ref List<Dictionary<string, object>> chlist)
        {
            var dr = table.Select("parentMenu='" + menuCode + "'");
            if (dr.Length > 0)
            {
                var cMenus = dr.OrderBy(x => x["orderNum"]).CopyToDataTable();
                for (int x = 0; x < cMenus.Rows.Count; x++)
                {
                    List<Dictionary<string, object>> tempList = new List<Dictionary<string, object>>();
                    var cdic = new Dictionary<string, object>();
                    cdic["menuName"] = cMenus.Rows[x]["menuName"].ToString();
                    cdic["menuIcon"] = cMenus.Rows[x]["menuIcon"].ToString();
                    if (cMenus.Rows[x]["onclick"] == null || string.IsNullOrWhiteSpace(cMenus.Rows[x]["onclick"].ToString()))
                    {
                        cdic["onclick"] = "";
                    }
                    else
                    {
                        cdic["onclick"] = cMenus.Rows[x]["onclick"].ToString();
                    }
                    cdic["url"] = cMenus.Rows[x]["menuPath"].ToString();

                    ChildUrl(table, cMenus.Rows[x]["menuCode"].ToString(), cMenus.Rows[x]["menuName"].ToString(), cMenus.Rows[x]["menuIcon"].ToString(), ref tempList);
                    cdic["child"] = tempList;
                    chlist.Add(cdic);

                }

            }


        }
    
       
        
     
        
        /// <summary>
        /// 系统登录方法(统一)
        /// </summary>
        /// <param name="userCode">登录账号</param>
        /// <param name="pwd">登录密码</param>
        /// <param name="loginType">登录类型</param>
        /// <returns></returns>
        public ReturnResult login(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "参数丢失";
                    return rsl;
                }
                var json = JsonConvert.DeserializeObject<JObject>(jsonStr);
                if (string.IsNullOrWhiteSpace(json["userCode"].ToString()))
                {
                    rsl.Message = "登录账号不允许为空";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(json["userPwd"].ToString()))
                {
                    rsl.Message = "登录密码不允许为空";
                    return rsl;
                }
                DbUser user = new DbUser();
                user.userCode = json["userCode"].ToString().Trim();
                user.userPwd = Tools.Encryption.DesEncrypt(json["userPwd"].ToString().Trim());
                user.status = "Y";
                var list = cmd.GetDataByObject<LoginUser>(user);
                if (list.Count > 0)
                {
                    string sql = "select * from sys_CustomerBase_info where dbCode='"+ json["baseCode"] +"'";
                    var bTable = cmd.GetDataTable(sql);
                    if (bTable.Rows.Count > 0)
                    {
                        var arr = bTable.Rows[0]["baseName"].ToString().Split('_');
                        if (arr.Length < 3)
                        {
                            rsl.Message = "账号密码验证通过，但关联账套设置有误";
                            return rsl;
                        }
                        else
                        {
                            list[0].baseCode = arr[1];
                        }
                    }
                    
                    rsl.Data = list[0];
                    rsl.Result = true;
                }
                else
                {
                    rsl.Message = "账号或密码错误";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
       
    
        /// <summary>
        /// 获取当前登录人信息
        /// </summary>
        /// <returns></returns>
        public LoginUser getLoginInfo()
        {
            return userLogin.UserInfo();
        }
        

      
        

      
       
        
        /// <summary>
        /// 菜单数据列表显示
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
       

    
        /// <summary>
        /// 获取指定菜单的现有操作权限
        /// </summary>
        /// <param name="menuCode">菜单编码</param>
        /// <returns></returns>
        
       
        /// <summary>
        /// 菜单删除方法
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult DelMenuInfo(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                DbMenuInfo menu = new DbMenuInfo();
                menu.id = int.Parse(dataId);
                menu.isdel = 1;
                menu.deldate = getNow();
                menu.deluser = userLogin.UserInfo().userCode;
                oper = new OperateModel();
                oper.Conditions = "id";
                oper.Data = menu;
                oper.Types = OperateModel.OperateType.Edit;
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        #region LayUiTree代码
        /// <summary>
        /// layui树结构
        /// </summary>
        /// <param name="usCode"></param>
        /// <returns></returns>
        public ReturnResult layUiTree(string usCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from sys_MenuInfo ");
                sb.Append(" where status='Y' and isdel=0 ");
                var table = cmd.GetDataTable(sb.ToString());//获取菜单全部信息
                rsl.Data = LayUiList(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 创建导航数据
        /// </summary>
        /// <param name="table">数据源</param>
        /// <returns></returns>
        private List<Dictionary<string, object>> LayUiList(DataTable table)
        {
            List<Dictionary<string, object>> menuList = new List<Dictionary<string, object>>();
            #region 构建数据
            var fMenu = table.Select("menuLevel=1 and mType='pc'").OrderBy(x => x["orderNum"]).CopyToDataTable();//获取所有父级菜单
            for (int i = 0; i < fMenu.Rows.Count; i++)
            {
                var fdic = new Dictionary<string, object>();
                fdic["title"] = fMenu.Rows[i]["menuName"].ToString();
                fdic["id"] = fMenu.Rows[i]["menuCode"].ToString();

                #region 子菜单
                List<Dictionary<string, object>> cList = new List<Dictionary<string, object>>();
                this.LayChildUrl(table, fMenu.Rows[i]["menuCode"].ToString(), fMenu.Rows[i]["menuName"].ToString(), ref cList);
                fdic["children"] = cList;
                #endregion
                menuList.Add(fdic);
            }
            var mdic = new Dictionary<string, object>();
            mdic["title"] = "移动端权限";
            mdic["id"] = "ydapp";
            StringBuilder sb = new StringBuilder();
            var mpDr = table.Select("mType='APP' and menuLevel='1'");
            List<Dictionary<string, object>> apList = new List<Dictionary<string, object>>();
            if (mpDr.Length> 0)
            {
                Dictionary<string, object> adic;
                foreach (DataRow r in mpDr)
                {
                    adic = new Dictionary<string, object>();
                    adic["title"] = r["menuName"].ToString();
                    adic["id"] = r["menuCode"].ToString();
                    #region 子菜单
                    List<Dictionary<string, object>> cList = new List<Dictionary<string, object>>();
                    this.LayChildUrl(table, r["menuCode"].ToString(), r["menuCode"].ToString(), ref cList);
                    adic["children"] = cList;
                    if (cList == null || cList.Count < 1)
                    {
                        adic["operate"] = r["operate"].ToString();
                    }
                    #endregion
                    apList.Add(adic);
                }
            }

            mdic["children"] = apList;

            menuList.Add(mdic);
            #endregion
            return menuList;
        }
        /// <summary>
        /// 子菜单生成方法(递归)
        /// </summary>
        /// <param name="table"></param>
        /// <param name="menuCode"></param>
        /// <param name="menuName"></param>
        /// <param name="icon"></param>
        /// <param name="chlist"></param>
        private void LayChildUrl(DataTable table, string menuCode, string menuName, ref List<Dictionary<string, object>> chlist)
        {
            var dr = table.Select("parentMenu='" + menuCode + "'");
            if (dr.Length > 0)
            {
                var cMenus = dr.OrderBy(x => x["orderNum"]).CopyToDataTable();
                for (int x = 0; x < cMenus.Rows.Count; x++)
                {
                    List<Dictionary<string, object>> tempList = new List<Dictionary<string, object>>();
                    var cdic = new Dictionary<string, object>();
                    cdic["title"] = cMenus.Rows[x]["menuName"].ToString();
                    cdic["id"] = cMenus.Rows[x]["menuCode"].ToString();
                    LayChildUrl(table, cMenus.Rows[x]["menuCode"].ToString(), cMenus.Rows[x]["menuName"].ToString(), ref tempList);
                    cdic["children"] = tempList;
                    cdic["operate"] = cMenus.Rows[x]["operate"].ToString();
                    chlist.Add(cdic);

                }

            }


        }

        #endregion

        /// <summary>
        /// 获取用户权限
        /// </summary>
        /// <param name="userCode">用户编码(为空时查询当前登录人权限)</param>
        /// <param name="menuCode">菜单编码</param>
        /// <returns></returns>
        public ReturnResult getUserPower(string userCode, string menuCode)
        {
            rsl = new ReturnResult();
            try
            {
                string isAdmin = "";
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(userCode))
                {
                    userCode = userLogin.UserInfo().userCode;
                    isAdmin = userLogin.UserInfo().isAdmin.ToString();
                }
                else
                {
                    sb.Append("select isAdmin from sys_users_info where userCode='" + userCode + "' ");
                    var table = cmd.GetDataTable(sb.ToString());
                    if(table.Rows.Count<=0){
                        rsl.Result = false;
                        rsl.Message = "没有获取人员:"+userCode+"的信息";
                        return rsl;
                    }
                    isAdmin = table.Rows[0][0].ToString();
                }
                sb.Clear();
                if (isAdmin != "1")
                {
                    #region 非管理员-根据权限获取全部权限
                    sb.Append("select top 1 * from sys_powerConfig_users where ");
                    sb.Append(" userCode='" + userCode.Trim() + "' and ");
                    sb.Append("menuCode='" + menuCode + "'");
                    var table = cmd.GetDataTable(sb.ToString());
                    rsl.Result = true;
                    if (table.Rows.Count > 0)
                    {
                        rsl.Data = table.Rows[0]["operates"].ToString().ToLower();
                    }
                    else
                    {
                        rsl.Data = "";
                        rsl.Message = "没有数据";
                    }
                    #endregion
                }
                else
                {
                    #region 管理员权限
                    sb.Append("select isnull(operate,'') oper from sys_MenuInfo where menuCode='" + menuCode + "'");
                    var table = cmd.GetDataTable(sb.ToString());
                    if (table.Rows.Count > 0 && !string.IsNullOrWhiteSpace(table.Rows[0][0].ToString()))
                    {
                        rsl.Data = table.Rows[0][0].ToString().Split(';')[0].ToLower();
                        rsl.Result = true;
                    }
                    else
                    {
                        rsl.Data = "";
                    }
                    #endregion
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 用户权限保存方法
        /// </summary>
        /// <param name="userCode">用户</param>
        /// <param name="menuCode">菜单编码</param>
        /// <param name="powers">权限</param>
        /// <returns></returns>
        public ReturnResult saveUserPower(string userCode, string menuCode, string powers)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(userCode))
                {
                    rsl.Message = "用户不能为空"; return rsl;
                }
                if (string.IsNullOrWhiteSpace(powers))
                {
                    sb.Append("delete from sys_powerConfig_users where ");
                    sb.Append(" userCode='" + userCode.Trim() + "' and ");
                    sb.Append("menuCode='" + menuCode + "'");
                    rsl = cmd.UpdateSql(sb.ToString());
                }
                else
                {

                    sb.Append("select top 1 * from sys_powerConfig_users where ");
                    sb.Append(" userCode='" + userCode.Trim() + "' and ");
                    sb.Append("menuCode='" + menuCode + "'");
                    var table = cmd.GetDataTable(sb.ToString());
                    bool isAdd = true;
                    if (table.Rows.Count > 1)
                    {
                        rsl.Message = "权限存在重复"; return rsl;
                    }
                    else
                    {
                        if (table.Rows.Count > 0)
                        {
                            isAdd = false;
                        }
                    }
                    #region 更新方法
                    DbUserPowers p = new DbUserPowers();
                    p.menuCode = menuCode;
                    p.operates = powers;
                    p.userCode = userCode;
                    if (isAdd)
                    {
                        p.createtime = DateTime.Now.ToString();
                        p.createuser = userLogin.UserInfo().userCode;
                        rsl = cmd.Add(p);
                    }
                    else
                    {
                        OperateModel oper = new OperateModel();
                        oper.Data = p;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "userCode,menuCode";
                        rsl = cmd.Edit(oper);
                    }
                    #endregion
                }


            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

       
 

   
        /// <summary>
        /// 删除账套信息(物理删除)
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult DelCustomBase(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(dataId))
                {
                    rsl.Message = "参数丢失";
                    return rsl;
                }
                string sql = "delete from sys_CustomerBase_info where id=" + dataId;
                rsl = cmd.UpdateSql(sql);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

    
    }
}
